var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");

// var min = 1;

var max = 3;

myCanvas.width = document.documentElement.clientWidth;

myCanvas.height = document.documentElement.clientHeight;

function Ball() {
    this.centerX = getRandom(max, myCanvas.width - max);

    this.centerY = getRandom(max, myCanvas.height - max);

    this.radius = getRandom(1, 3);

    this.color = getRandomColor();

    var speed1 = getRandom(1, 1);

    this.speedX = getRandom(0, 1) ? -speed1 : speed1;

    var speed2 = getRandom(1, 1);

    this.speedY = getRandom(0, 1) ? -speed2 : speed2;
}

Ball.prototype.move = function () {
    this.centerX += this.speedX;

    this.centerY += this.speedY;
};

Ball.prototype.draw = function () {
    ctx.beginPath();

    ctx.arc(this.centerX, this.centerY, this.radius, 0, Math.PI * 2, false);

    ctx.closePath();

    ctx.fillStyle = this.color;

    ctx.fill();
};

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function getRandomColor() {
    // var red = getRandom(0, 255);

    // var green = getRandom(0, 255);

    // var blue = getRandom(0, 255);
    // return "#006A9C";
    return "#76A6FB";
    // return "rgb(" + red + "," + green + "," + blue + ")";
}

//   var count = 1000;
var count = 200;

var balls = [];

for (var i = 0; i < count; i++) {
    var ball = new Ball();

    balls.push(ball);
}

console.log(balls);

function startAnimation() {
    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);

    ctx.font = "100px STKaiTi";

    ctx.strokeStyle = "white";

    // ctx.strokeText("SQ", myCanvas.width / 2.2, myCanvas.height / 2, 500);

    for (i = 0; i < balls.length; i++) {
        balls[i].move();

        balls[i].draw();
    }

    adjustPB();
}

setInterval(() => {
    startAnimation()
}, 50);

//碰壁反弹

function adjustPB() {
    for (i = 0; i < balls.length; i++) {
        if (
            balls[i].centerX <= balls[i].radius ||
            balls[i].centerX >= myCanvas.width - balls[i].radius
        ) {
            balls[i].speedX *= -1;
        }

        if (
            balls[i].centerY <= balls[i].radius ||
            balls[i].centerY >= myCanvas.height - balls[i].radius
        ) {
            balls[i].speedY *= -1;
        }
    }
}